﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.POIFS.FileSystem;
using NPOI.XSSF.UserModel;


namespace ReadPointsRingNumberExcel
{
    public class ReadExcel
    {
        private ISheet sheet;
        public ReadExcel(string path = "")
        {
            this.openFile(path);
        }
        private void openFile(string path)
        {
            using (FileStream file = new FileStream(path, FileMode.Open))
            {
                var fileInfo = new FileInfo(path);
                try
                {
                    if (fileInfo.Extension == ".xls")
                    {
                        var hssfworkbook = new HSSFWorkbook(file);
                        this.sheet = hssfworkbook.GetSheetAt(0);
                    }
                    else if (fileInfo.Extension == ".xlsx")
                    {
                        var hssfworkbook = new XSSFWorkbook(file);
                        this.sheet = hssfworkbook.GetSheetAt(0);
                    }
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                }
            }
        }

        public List<RingConfig> ReadFile()
        {
            
            var startRow = 0;
            var go = true;
            var list = new List<RingConfig>();
            do
            {
                var txt = sheet.GetCellText(startRow, 0);
                if (txt != "")
                {
                    var ringCell = sheet.GetCell(startRow, 1);
                    var item = new RingConfig()
                    {
                        Name = txt,
                        RingNumber = ringCell.CellType == CellType.Numeric ?
                            sheet.GetCellNumber(startRow, 1).ToString() : sheet.GetCellText(startRow, 1),
                        Mile = ringCell.CellType == CellType.Numeric ?
                            sheet.GetCellNumber(startRow, 2).ToString() : sheet.GetCellText(startRow, 2)
                    };
                    item.Mile = item.Mile == "" ? "0" : item.Mile;
                    list.Add(item);
                    startRow++;
                }
                else
                {
                    go = false;
                }

            } while (go == true);
            return list;
        }
    }
}
